// 键值编辑器
import React from 'react';
import { Button, Input, Form } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import style from './style.module.less';

export interface KeyEditorItem {
  label: string;
  value: string;
}

export default (props: { name: string; prop?: KeyEditorItem }) => {
  const prop = props?.prop ?? { label: 'label', value: 'value' };

  return (
    <Form.List name={props.name}>
      {(fields, { add, remove }) => {
        return (
          <div className={style.list}>
            {fields &&
              Array.isArray(fields) &&
              fields.map((item: any, i) => {
                return (
                  <div key={item.key} className={style.listItem}>
                    <Form.Item
                      name={[item.name, prop.label]}
                      fieldKey={[item.fieldKey, prop.label]}
                      label={'键名'}
                    >
                      <Input />
                    </Form.Item>

                    <Form.Item
                      name={[item.name, prop.value]}
                      fieldKey={[item.fieldKey, prop.value]}
                      label={'键值'}
                    >
                      <Input />
                    </Form.Item>

                    <div className={style.remove} onClick={() => remove(i)}>
                      <DeleteOutlined />
                    </div>
                  </div>
                );
              })}

            <div className={style.append}>
              <Button
                size={'small'}
                icon={<PlusOutlined />}
                onClick={() => add({ [prop.label]: '', [prop.value]: '' })}
              >
                添加
              </Button>
            </div>
          </div>
        );
      }}
    </Form.List>
  );
};
